import fs from 'fs-extra';
import path from "path";
import { BaseTask, TaskResult } from "../../common/tasks/BastTask.js";
import { PrebuildAppData, PreBuildAppTask } from '../../common/tasks/PreBuildAppTask.js';
import { WrapCSharpTask } from '../../common/tasks/WrapCSharpTask.js';
import { toolchain } from '../../toolchain.js';
import { Nullable } from '../../typings';
import { SetScriptDefineTask } from '../../common/tasks/SetScriptDefineTask.js';

export interface BuildUnityResult {
    version: string
}

export abstract class WebGLBuildUnityBaseTask extends BaseTask<BuildUnityResult> {
    async callUnity(output: string, buildCommand: 'BuildForWebGL' | 'BuildForMiniGame' | 'BuildForDouyin'): Promise<TaskResult<BuildUnityResult>> {
        const outputPath = path.join(toolchain.params.workSpacePath, output);
        if (buildCommand != 'BuildForDouyin') {
            await fs.emptyDir(outputPath);
        }
        await fs.ensureDir(outputPath);

        const channelCfg = toolchain.params.channelCfg;
        const prebuildResult = toolchain.taskHelper.getResult<PrebuildAppData>(PreBuildAppTask.name);
        const version = (channelCfg.bundleVersion ?? toolchain.params.version) + '.' + prebuildResult!.data!.versionCode;

        const params = ['-batchmode', '-projectPath', toolchain.params.workSpacePath, '-executeMethod', `BuildCommand.${buildCommand}`,
            '-defines', prebuildResult!.data!.defines, '-numberversion', version, '-bundleId', channelCfg.bundleId, '-productName', channelCfg.productName.replace(/ /g, '%20'), '-path', outputPath, '-quit'];
        await toolchain.unity.runUnityCommand(this.cmdOption, params, 'WEBGL');

        return { success: true, errorCode: 0, data: { version } };
    }

    get dependencies(): Nullable<string[]> {
        return [SetScriptDefineTask.name, WrapCSharpTask.name, PreBuildAppTask.name];
    }

    get skip(): boolean {
        return !this.cmdOption.buildExe;
    }
}
